package threadLearn.future;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UseFuture {
	
	public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
		
		Long start = System.currentTimeMillis();
		Callable<String> riceCall = new Callable<String>() {

			@Override
			public String call() throws Exception {

				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				return "准备好了饭。。。";
			}
		};
		
		FutureTask<String> ft1 = new FutureTask<>(riceCall);
		new Thread(ft1).start();
		
		Callable<String> dishCall = new Callable<String>() {

			@Override
			public String call() throws Exception {
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				return "准备好了菜。。。";
			}
		};
		
		FutureTask<String> ft2 = new FutureTask<>(dishCall);
		new Thread(ft2).start();
		
		System.out.println(ft1.get(6, TimeUnit.SECONDS));//get方法会阻塞当前线程知道返回结果
		System.out.println(ft2.get(1, TimeUnit.SECONDS));//get(1, TimeUnit.SECONDS) 一秒内没有得到结果就抛出超时异常
		System.out.println("耗时："+(System.currentTimeMillis()-start));

	}

}
